#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/11/20 下午10:19
    Desc  :
--------------------------------------
"""
import json
import time
import uuid

from django.utils.deprecation import MiddlewareMixin

from common.utils.jwt_utils import AuthJwt
from common.utils.log_utils import logger, thread_log
from person.tasks import add_log_task
from platform_auth.settings import LOG_BLACK_LIST


class LogMiddleware(MiddlewareMixin):
    def __init__(self, get_reponse=None):
        super(LogMiddleware, self).__init__()
        self.get_response = get_reponse
        self.startTime = int(time.time() * 1000),
        self._body = None

    def request_log(self, request, response):
        username, userId = AuthJwt(request = request).get_user_id_and_username()
        data = {
            'path': str(request.path),
            'method': str(request.method),
            'scheme': str(request.scheme),
            'ip': request.headers.get('X-Real-Ip') if request.headers.get('X-Real-Ip') else request.META['REMOTE_ADDR'],
            'status': int(response.status_code),
            'request_body': self._body,
            'request_header': dict(request.headers),
            'response_body': str(response.content, encoding = 'utf-8') if str(
                request.path) not in LOG_BLACK_LIST else None,
            'response_header': dict(response.headers),
            'startTime': self.startTime[0],
            'endTime': int(time.time() * 1000),
            'operateType': None,
            'operatorId': userId,
            'operateContent': None,
            'operatorName': username,
            'operateTime': int(time.time() * 1000),
        }

        return data

    def process_request(self, request):
        thread_log.traceId = str(uuid.uuid4())[-12:]
        thread_log.requestInfo = f"{request.method} {request.path}"

        self._body = getattr(request, '_body', request.body)
        self._body = str(self._body, encoding = "utf-8") if str(request.path) not in LOG_BLACK_LIST else None

    def process_response(self, request, response):
        data = self.request_log(request, response)

        query = request.META.get('QUERY_STRING', None)
        if query:
            query = f'?{query}'
        else:
            query = ''

        thread_log.requestInfo = f"{request.method} {request.path}{query} {response.status_code}"
        logger.info(f'请求头: {request.headers}')
        logger.info(f'请求参数: {data.get("request_body")}')
        if request.path not in LOG_BLACK_LIST and int(response.status_code) == 200:
            add_log_task.delay(data)
        logger.info(f'响应: {str(response.content, encoding = "utf-8")}')

        return response
